<template>
  <div class="diet-plan-system">
    <!-- 主页面 -->
    <div class="main-page" v-if="!dialogVisible">
      <div class="header">
        <h1>膳食计划管理</h1>
        <el-button type="primary" @click="showDialog('create')">新建计划</el-button>
      </div>

      <div class="plan-list">
        <h2>档案编码</h2>
        <div class="plan-item" v-for="plan in planList" :key="plan.code">
          <div class="plan-code">{{ plan.code }}</div>
          <div class="plan-info">
            <div>{{ plan.name }}</div>
            <div>{{ plan.gender }}</div>
            <div>{{ plan.careLevel }}</div>
            <div :class="{'status-planned': plan.status === '已计划',
                         'status-unplanned': plan.status === '未计划',
                         'status-expired': plan.status === '计划过期'}">
              {{ plan.status }}
            </div>
            <div>{{ plan.createTime }}</div>
          </div>
          <div class="plan-actions">
            <el-button size="small" @click="showDialog('view', plan)">查看</el-button>
            <el-button size="small" type="primary" @click="showDialog('edit', plan)">编辑</el-button>
            <el-button size="small" type="danger" @click="deletePlan(plan)">删除</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 对话框容器 -->
    <div class="dialog-container" v-if="dialogVisible">
      <!-- 新建计划对话框 -->
      <div class="create-dialog" v-if="dialogType === 'create'">
        <h1>请选择老人</h1>

        <div class="elder-selection">
          <h2>档案编码</h2>
          <el-select v-model="newPlan.elderId" placeholder="请选择老人" class="elder-select">
            <el-option
                v-for="elder in elderList"
                :key="elder.id"
                :label="`${elder.name} (${elder.code})`"
                :value="elder.id"
            />
          </el-select>

          <div class="elder-info" v-if="selectedElder">
            <div>老人姓名: {{ selectedElder.name }}</div>
            <div>性别: {{ selectedElder.gender }}</div>
            <div>护理级别: {{ selectedElder.careLevel }}</div>
            <div>计划状态: {{ selectedElder.status }}</div>
            <div>饮食习惯: {{ selectedElder.eatingHabits }}</div>
          </div>
        </div>

        <div class="diet-plan-section">
          <h2>膳食计划</h2>
          <p>1. 调整膳食计划。根据个体的反馈和需要，对膳食计划进行调整，以确保其适合个体需求。</p>

          <el-divider />

          <div class="plan-period">
            <h3>计划周期：</h3>
            <el-date-picker
                v-model="newPlan.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            />
          </div>

          <div class="auto-renewal">
            <h3>到期后，自动以</h3>
            <el-select v-model="newPlan.cycle" placeholder="请选择周期">
              <el-option label="三天" value="三天" />
              <el-option label="七天" value="七天" />
              <el-option label="十五天" value="十五天" />
              <el-option label="一个月" value="一个月" />
            </el-select>
            <h3>为一周期循环更新计划</h3>
          </div>

          <div class="responsible-nurse">
            <h3>责任护士：</h3>
            <el-select v-model="newPlan.nurse" placeholder="请选择护士">
              <el-option
                  v-for="nurse in nurseList"
                  :key="nurse.id"
                  :label="nurse.name"
                  :value="nurse.id"
              />
            </el-select>
          </div>

          <el-divider />

          <div class="meal-selection">
            <div class="meal-time">
              <h3>早上配餐：</h3>
              <el-select
                  v-model="newPlan.breakfast"
                  multiple
                  placeholder="请选择膳食"
                  @change="updateSelectedMeals"
              >
                <el-option
                    v-for="meal in mealOptions"
                    :key="meal.id"
                    :label="meal.name"
                    :value="meal.id"
                />
              </el-select>
            </div>

            <div class="meal-time">
              <h3>中午配餐：</h3>
              <el-select
                  v-model="newPlan.lunch"
                  multiple
                  placeholder="请选择膳食"
                  @change="updateSelectedMeals"
              >
                <el-option
                    v-for="meal in mealOptions"
                    :key="meal.id"
                    :label="meal.name"
                    :value="meal.id"
                />
              </el-select>
            </div>

            <div class="meal-time">
              <h3>晚上配餐：</h3>
              <el-select
                  v-model="newPlan.dinner"
                  multiple
                  placeholder="请选择膳食"
                  @change="updateSelectedMeals"
              >
                <el-option
                    v-for="meal in mealOptions"
                    :key="meal.id"
                    :label="meal.name"
                    :value="meal.id"
                />
              </el-select>
            </div>
          </div>

          <el-divider />

          <div class="selected-meals-section">
            <h3>已选膳食区域</h3>
            <div class="selected-meals">
              <div v-for="meal in selectedMeals" :key="meal.id" class="meal-item">
                {{ meal.name }}
              </div>
            </div>
          </div>
        </div>

        <div class="dialog-actions">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="createPlan">确定</el-button>
        </div>
      </div>

      <!-- 查看计划对话框 -->
      <div class="view-dialog" v-if="dialogType === 'view'">
        <h1>老人信息</h1>

        <el-descriptions :column="1" border>
          <el-descriptions-item label="档案编码">{{ currentPlan.code }}</el-descriptions-item>
          <el-descriptions-item label="老人姓名">{{ currentPlan.name }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentPlan.gender }}</el-descriptions-item>
          <el-descriptions-item label="护理级别">{{ currentPlan.careLevel }}</el-descriptions-item>
          <el-descriptions-item label="计划状态">{{ currentPlan.status }}</el-descriptions-item>
          <el-descriptions-item label="饮食习惯">{{ currentPlan.eatingHabits }}</el-descriptions-item>
        </el-descriptions>

        <div class="diet-plan-section">
          <h2>膳食计划</h2>
          <p>1. 调整膳食计划。根据个体的反馈和需要，对膳食计划进行调整，以确保其适合个体需求。</p>

          <el-divider />

          <div class="plan-period">
            <h3>计划周期：</h3>
            <p>{{ currentPlan.startDate }} 至 {{ currentPlan.endDate }}</p>
          </div>

          <div class="auto-renewal">
            <h3>到期后，自动以 {{ currentPlan.cycle }} 为一周期循环更新计划</h3>
          </div>

          <div class="responsible-nurse">
            <h3>责任护士：</h3>
            <p>{{ currentPlan.nurse }}</p>
          </div>

          <el-divider />

          <div class="meal-plan">
            <div class="meal-time">
              <h3>早上配餐：</h3>
              <ul>
                <li v-for="(item, index) in currentPlan.breakfast" :key="index">{{ item }}</li>
              </ul>
            </div>

            <div class="meal-time">
              <h3>中午配餐：</h3>
              <ul>
                <li v-for="(item, index) in currentPlan.lunch" :key="index">{{ item }}</li>
              </ul>
            </div>

            <div class="meal-time">
              <h3>晚上配餐：</h3>
              <ul>
                <li v-for="(item, index) in currentPlan.dinner" :key="index">{{ item }}</li>
              </ul>
            </div>
          </div>
        </div>

        <div class="dialog-actions">
          <el-button @click="closeDialog">关闭</el-button>
        </div>
      </div>

      <!-- 编辑计划对话框 -->
      <div class="edit-dialog" v-if="dialogType === 'edit'">
        <h1>老人信息</h1>

        <el-descriptions :column="1" border>
          <el-descriptions-item label="档案编码">{{ currentPlan.code }}</el-descriptions-item>
          <el-descriptions-item label="老人姓名">{{ currentPlan.name }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentPlan.gender }}</el-descriptions-item>
          <el-descriptions-item label="护理级别">{{ currentPlan.careLevel }}</el-descriptions-item>
          <el-descriptions-item label="计划状态">{{ currentPlan.status }}</el-descriptions-item>
          <el-descriptions-item label="饮食习惯">{{ currentPlan.eatingHabits }}</el-descriptions-item>
        </el-descriptions>

        <div class="diet-plan-section">
          <h2>膳食计划</h2>
          <p>1. 调整膳食计划。根据个体的反馈和需要，对膳食计划进行调整，以确保其适合个体需求。</p>

          <el-divider />

          <div class="plan-period">
            <h3>计划周期：</h3>
            <el-date-picker
                v-model="editPlan.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            />
          </div>

          <div class="auto-renewal">
            <h3>到期后，自动以</h3>
            <el-select v-model="editPlan.cycle" placeholder="请选择周期">
              <el-option label="三天" value="三天" />
              <el-option label="七天" value="七天" />
              <el-option label="十五天" value="十五天" />
              <el-option label="一个月" value="一个月" />
            </el-select>
            <h3>为一周期循环更新计划</h3>
          </div>

          <div class="responsible-nurse">
            <h3>责任护士：</h3>
            <el-select v-model="editPlan.nurse" placeholder="请选择护士">
              <el-option
                  v-for="nurse in nurseList"
                  :key="nurse.id"
                  :label="nurse.name"
                  :value="nurse.id"
              />
            </el-select>
          </div>

          <el-divider />

          <div class="meal-selection">
            <div class="meal-time">
              <h3>早上配餐：</h3>
              <el-select
                  v-model="editPlan.breakfast"
                  multiple
                  placeholder="请选择膳食"
                  @change="updateSelectedMeals"
              >
                <el-option
                    v-for="meal in mealOptions"
                    :key="meal.id"
                    :label="meal.name"
                    :value="meal.id"
                />
              </el-select>
            </div>

            <div class="meal-time">
              <h3>中午配餐：</h3>
              <el-select
                  v-model="editPlan.lunch"
                  multiple
                  placeholder="请选择膳食"
                  @change="updateSelectedMeals"
              >
                <el-option
                    v-for="meal in mealOptions"
                    :key="meal.id"
                    :label="meal.name"
                    :value="meal.id"
                />
              </el-select>
            </div>

            <div class="meal-time">
              <h3>晚上配餐：</h3>
              <el-select
                  v-model="editPlan.dinner"
                  multiple
                  placeholder="请选择膳食"
                  @change="updateSelectedMeals"
              >
                <el-option
                    v-for="meal in mealOptions"
                    :key="meal.id"
                    :label="meal.name"
                    :value="meal.id"
                />
              </el-select>
            </div>
          </div>

          <el-divider />

          <div class="selected-meals-section">
            <h3>已选膳食区域</h3>
            <div class="selected-meals">
              <div v-for="meal in selectedMeals" :key="meal.id" class="meal-item">
                {{ meal.name }}
              </div>
            </div>
          </div>
        </div>

        <div class="dialog-actions">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="updatePlan">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, reactive, computed, onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";

export default {
  setup() {
    // 计划列表数据
    const planList = ref([
      {
        code: 'JK201806061552001',
        name: '刘晓龙',
        gender: '女',
        careLevel: '三级护理',
        status: '已计划',
        createTime: '2018-06-06 09:01:50',
        eatingHabits: '素食为主、营养均衡',
        cycle: '三天',
        nurse: '刘护工',
        breakfast: ['馒头*1', '鸡蛋*1', '牛奶*1'],
        lunch: ['川普辣子鸡*1', '玉米炖排骨*1'],
        dinner: ['川普辣子鸡*1', '玉米炖排骨*1'],
        startDate: '2018-06-06',
        endDate: '2018-07-06'
      },
      {
        code: 'JK201806061552002',
        name: '李爷爷',
        gender: '男',
        careLevel: '三级护理',
        status: '已计划',
        createTime: '2018-06-06 09:01:50',
        eatingHabits: '普通饮食',
        cycle: '七天',
        nurse: '张护工',
        breakfast: ['包子*1', '豆浆*1'],
        lunch: ['红烧肉*1', '青菜*1'],
        dinner: ['清蒸鱼*1', '米饭*1'],
        startDate: '2018-06-06',
        endDate: '2018-07-06'
      },
      {
        code: 'JK201806061552003',
        name: '张奶奶',
        gender: '女',
        careLevel: '三级护理',
        status: '已计划',
        createTime: '2018-06-06 09:01:50',
        eatingHabits: '低盐低脂',
        cycle: '十五天',
        nurse: '王护工',
        breakfast: ['燕麦粥*1', '鸡蛋*1'],
        lunch: ['清蒸鱼*1', '青菜*1'],
        dinner: ['小米粥*1', '花卷*1'],
        startDate: '2018-06-06',
        endDate: '2018-07-06'
      },
      {
        code: 'JK201806061552006',
        name: '李爷爷',
        gender: '男',
        careLevel: '二级护理',
        status: '未计划',
        createTime: '2018-06-06 09:01:50',
        eatingHabits: '普通饮食',
        cycle: '',
        nurse: '',
        breakfast: [],
        lunch: [],
        dinner: [],
        startDate: '',
        endDate: ''
      },
      {
        code: 'JK201806061552010',
        name: '李爷爷',
        gender: '男',
        careLevel: '特级护理',
        status: '计划过期',
        createTime: '2018-06-06 09:01:50',
        eatingHabits: '流质饮食',
        cycle: '三天',
        nurse: '李护工',
        breakfast: ['米汤*1', '蛋白粉*1'],
        lunch: ['肉泥*1', '菜泥*1'],
        dinner: ['米糊*1', '果汁*1'],
        startDate: '2018-06-06',
        endDate: '2018-07-06'
      }
    ])

    // 老人列表数据
    const elderList = ref([
     { id: '1', code: 'JK201806061552001', name: '刘晓龙', gender: '女', careLevel: '三级护理', status: '已计划', eatingHabits: '素食为主、营养均衡' },
     { id: '2', code: 'JK201806061552002', name: '李爷爷', gender: '男', careLevel: '三级护理', status: '已计划', eatingHabits: '普通饮食' },
     { id: '3', code: 'JK201806061552003', name: '张奶奶', gender: '女', careLevel: '三级护理', status: '已计划', eatingHabits: '低盐低脂' },
     { id: '4', code: 'JK201806061552004', name: '李爷爷', gender: '男', careLevel: '二级护理', status: '已计划', eatingHabits: '普通饮食' },
     { id: '5', code: 'JK201806061552006', name: '李爷爷', gender: '男', careLevel: '二级护理', status: '未计划', eatingHabits: '普通饮食' },
     { id: '6', code: 'JK201806061552010', name: '李爷爷', gender: '男', careLevel: '特级护理', status: '计划过期', eatingHabits: '流质饮食' }
    ])

    // 护士列表数据
    const nurseList = ref([
      { id: '1', name: '刘护工' },
      { id: '2', name: '张护工' },
      { id: '3', name: '王护工' },
      { id: '4', name: '李护工' },
      { id: '5', name: '赵护工' }
    ])

    // 膳食选项数据
    const mealOptions = ref([])
    const loadMeals = () => {
      axios.get(BASE_URL + '/v1/meals/select?')
          .then((response) => {
            if (response.data.state == 2000) {
              mealOptions.value = response.data.data
            } else {
              ElMessage.error(response.data.msg)
            }
          })
    }
    //查询老人信息
    // const loadPatient = () => {
    //   axios.get(BASE_URL + '/v1/patient/select?')
    //       .then((response) => {
    //         if (response.data.state == 2000) {
    //           elderList.value = response.data.data
    //         } else {
    //           ElMessage.error(response.data.msg)
    //         }
    //       })
    // }

    onMounted(() => {
      loadMeals();
     // loadPatient();查询老人数据
    })

    // 对话框控制
    const dialogVisible = ref(false)
    const dialogType = ref('') // 'create', 'view', 'edit'
    const currentPlan = ref(null)

    // 新建计划表单
    const newPlan = reactive({
      elderId: '',
      dateRange: [],
      cycle: '三天',
      nurse: '',
      breakfast: [],
      lunch: [],
      dinner: []
    })

    // 编辑计划表单
    const editPlan = reactive({
      code: '',
      dateRange: [],
      cycle: '',
      nurse: '',
      breakfast: [],
      lunch: [],
      dinner: []
    })

    // 已选膳食
    const selectedMeals = ref([])

    // 计算选中的老人信息
    const selectedElder = computed(() => {
      return elderList.value.find(elder => elder.id === newPlan.elderId)
    })

    // 更新已选膳食
    const updateSelectedMeals = () => {
      let allSelected = []
      if (dialogType.value === 'create') {
        allSelected = [...newPlan.breakfast, ...newPlan.lunch, ...newPlan.dinner]
      } else if (dialogType.value === 'edit') {
        allSelected = [...editPlan.breakfast, ...editPlan.lunch, ...editPlan.dinner]
      }
      selectedMeals.value = mealOptions.value.filter(meal => allSelected.includes(meal.id))
    }

    // 显示对话框
    const showDialog = (type, plan = null) => {
      dialogType.value = type
      dialogVisible.value = true

      if (type === 'view' || type === 'edit') {
        currentPlan.value = plan
      }

      if (type === 'edit') {
        editPlan.code = plan.code
        editPlan.dateRange = [new Date(plan.startDate), new Date(plan.endDate)]
        editPlan.cycle = plan.cycle
        editPlan.nurse = nurseList.value.find(n => n.name === plan.nurse)?.id || ''
        editPlan.breakfast = plan.breakfast.map(item => {
          const meal = mealOptions.value.find(m => m.name === item)
          return meal ? meal.id : ''
        }).filter(Boolean)
        editPlan.lunch = plan.lunch.map(item => {
          const meal = mealOptions.value.find(m => m.name === item)
          return meal ? meal.id : ''
        }).filter(Boolean)
        editPlan.dinner = plan.dinner.map(item => {
          const meal = mealOptions.value.find(m => m.name === item)
          return meal ? meal.id : ''
        }).filter(Boolean)
        updateSelectedMeals()
      }
    }

    // 关闭对话框
    const closeDialog = () => {
      dialogVisible.value = false
      // 重置表单
      if (dialogType.value === 'create') {
        Object.assign(newPlan, {
          elderId: '',
          dateRange: [],
          cycle: '三天',
          nurse: '',
          breakfast: [],
          lunch: [],
          dinner: []
        })
      }
      selectedMeals.value = []
    }

    // 创建新计划
    const createPlan = () => {
      const elder = elderList.value.find(elder => elder.id === newPlan.elderId)
      const nurse = nurseList.value.find(nurse => nurse.id === newPlan.nurse)

      const plan = {
        code: `JK${new Date().getTime()}`,
        name: elder.name,
        gender: elder.gender,
        careLevel: elder.careLevel,
        status: '已计划',
        createTime: new Date().toLocaleString(),
        eatingHabits: elder.eatingHabits,
        cycle: newPlan.cycle,
        nurse: nurse.name,
        breakfast: newPlan.breakfast.map(id => mealOptions.value.find(meal => meal.id === id).name),
        lunch: newPlan.lunch.map(id => mealOptions.value.find(meal => meal.id === id).name),
        dinner: newPlan.dinner.map(id => mealOptions.value.find(meal => meal.id === id).name),
        startDate: newPlan.dateRange[0]?.toISOString().split('T')[0] || '',
        endDate: newPlan.dateRange[1]?.toISOString().split('T')[0] || ''
      }

      planList.value.unshift(plan)
      ElMessage.success('膳食计划创建成功')
      closeDialog()
    }

    // 更新计划
    const updatePlan = () => {
      const nurse = nurseList.value.find(nurse => nurse.id === editPlan.nurse)

      const updatedPlan = {
        ...currentPlan.value,
        cycle: editPlan.cycle,
        nurse: nurse.name,
        breakfast: editPlan.breakfast.map(id => mealOptions.value.find(meal => meal.id === id).name),
        lunch: editPlan.lunch.map(id => mealOptions.value.find(meal => meal.id === id).name),
        dinner: editPlan.dinner.map(id => mealOptions.value.find(meal => meal.id === id).name),
        startDate: editPlan.dateRange[0]?.toISOString().split('T')[0] || '',
        endDate: editPlan.dateRange[1]?.toISOString().split('T')[0] || ''
      }

      const index = planList.value.findIndex(p => p.code === currentPlan.value.code)
      if (index !== -1) {
        planList.value.splice(index, 1, updatedPlan)
      }

      ElMessage.success('膳食计划更新成功')
      closeDialog()
    }

    // 删除计划
    const deletePlan = (plan) => {
      ElMessageBox.confirm('确定要删除该膳食计划吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        planList.value = planList.value.filter(p => p.code !== plan.code)
        ElMessage.success('删除成功')
      }).catch(() => {
        // 取消删除
      })
    }

    return {
      planList,
      dialogVisible,
      dialogType,
      currentPlan,
      newPlan,
      editPlan,
      elderList,
      nurseList,
      mealOptions,
      selectedMeals,
      selectedElder,
      showDialog,
      closeDialog,
      createPlan,
      updatePlan,
      deletePlan,
      updateSelectedMeals
    }
  }
}
</script>

<style scoped>
.diet-plan-system {
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 主页面样式 */
.main-page {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.plan-list {
  margin-top: 20px;
}

.plan-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.plan-item:hover {
  background-color: #f5f7fa;
}

.plan-code {
  width: 200px;
  font-weight: bold;
}

.plan-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}

.plan-actions {
  width: 220px;
  display: flex;
  justify-content: flex-end;
}

.status-planned {
  color: #67c23a;
}

.status-unplanned {
  color: #909399;
}

.status-expired {
  color: #f56c6c;
}

/* 对话框通用样式 */
.dialog-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 新建/编辑对话框样式 */
.elder-select {
  width: 100%;
  margin-bottom: 15px;
}

.elder-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.elder-info div {
  margin-bottom: 5px;
}

.diet-plan-section {
  margin-top: 20px;
}

.plan-period,
.auto-renewal,
.responsible-nurse {
  margin-bottom: 20px;
}

.auto-renewal {
  display: flex;
  align-items: center;
  gap: 10px;
}

.meal-selection {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.meal-time h3 {
  margin-bottom: 10px;
}

.selected-meals-section {
  margin-top: 20px;
}

.selected-meals {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.meal-item {
  background-color: #f5f7fa;
  padding: 5px 10px;
  border-radius: 4px;
}

/* 查看对话框样式 */
.view-dialog .diet-plan-section {
  margin-top: 20px;
}

.view-dialog .plan-period,
.view-dialog .auto-renewal,
.view-dialog .responsible-nurse {
  margin-bottom: 20px;
}

.view-dialog .meal-plan {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.view-dialog .meal-time h3 {
  margin-bottom: 10px;
}

.view-dialog ul {
  padding-left: 20px;
  list-style-type: none;
}

.view-dialog li {
  margin-bottom: 5px;
}
</style>